package cn.edu.buaa.etei.native2ascii;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.ui.dialogs.PropertyPage;

public class Preference extends PropertyPage {
	
	private Button enableChk;

	public Preference(){
	}

	@Override
	protected Control createContents(Composite parent) {
		Composite composite = new Composite(parent,SWT.NULL);
		GridLayout layout = new GridLayout();
		layout.numColumns = 1;
		composite.setLayout(layout);
		enableChk = new Button(composite, SWT.CHECK);
		enableChk.setLayoutData(new GridData(SWT.BEGINNING, SWT.TOP, false,
				false));
		enableChk.setText("&Enable Native2Ascii properties bundle builder.");
		enableChk.setSelection(isBuilderEnalbed());
		return composite;
	}

	@Override
	public boolean performOk(){
		try {
			if(enableChk.getSelection()){
				Activator.addBuilder(getJavaProject());
			} else {
				Activator.removeBuilder(getJavaProject());
			}
			getJavaProject().getProject().build(IncrementalProjectBuilder.FULL_BUILD, null);
			return true;
		} catch (CoreException e) {
			ErrorDialog.openError(getShell(), "Error on applying setting", 
					"Exception thrown while save native2ascii builder setting.", 
					e.getStatus());
			return false;
		}
	}
	
	@Override
	public void performApply(){
		performOk();
	}
	
	@Override
	public void performDefaults(){
		enableChk.setSelection(false);
	}
	
	public IJavaProject getJavaProject(){
		return JavaCore.create((IProject) getElement());
	}
	
	public boolean isBuilderEnalbed() {
		try {
			return Activator.builderEnabled(getJavaProject());
		} catch (CoreException e) {
			ErrorDialog.openError(getShell(), "Error read native2ascii setting", 
					"Exception thrown while reading native2ascii builder setting", 
					e.getStatus());
		}
		return false;
	}
}
